package com.bskj.kuaifu.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.bean.model.TopupActivity;
import com.bskj.common.bean.model.UserInfo;
import com.bskj.common.bean.model.UserMoneyLog;
import com.bskj.common.dao.TopupActivityDao;
import com.bskj.common.dao.core.BaseDao;
import com.bskj.common.dao.core.FindRequestEntity;
import com.bskj.common.dao.core.OrderEnum;
import com.bskj.common.dao.core.WhereEnum;
import com.bskj.common.enums.TopupActivityStatusEnum;
import com.bskj.common.enums.TopupActivityTypeEnum;
import com.bskj.common.enums.UserMoneyChangeTypeEnum;
import com.bskj.common.service.impl.BaseServiceImpl;
import com.bskj.kuaifu.service.ITopupActivityService;
import com.bskj.kuaifu.service.IUserInfoService;
import com.bskj.kuaifu.service.IUserMoneyLogService;

@Service
public class TopupActivityServiceImpl extends BaseServiceImpl<TopupActivity> implements ITopupActivityService {
	@Autowired
	private TopupActivityDao topupActivityDao;

	@Autowired
	private IUserInfoService userInfoService;

	@Autowired
	private IUserMoneyLogService userMoneyLogService;

	@Override
	public BaseDao<TopupActivity> getBaseDao() {
		return topupActivityDao;
	}

	public List<TopupActivity> findActiveTopupActivity() throws Exception {
		FindRequestEntity findReq = new FindRequestEntity();
		findReq.addWhere("status", WhereEnum.EQ, TopupActivityStatusEnum.ACTIVE.getKey());
		findReq.addWhere("start_time", WhereEnum.LE, new Date());
		findReq.addWhere("end_time", WhereEnum.GE, new Date());
		findReq.addOrder("create_time", OrderEnum.DESC);
		return find(findReq);
	}

	@Transactional(rollbackFor = Exception.class)
	public void joinPayActivity(UserInfo userInfo, int topupMoney) throws Exception {
		if (userInfo == null)
			return;
		List<TopupActivity> activityList = findActiveTopupActivity();
		if (activityList != null && activityList.size() > 0) {
			for (TopupActivity topupActivity : activityList) {
				if (TopupActivityTypeEnum.ActivityType1.getKey() == topupActivity.getType()) {
					//充固定值，送固定的券。（现在只有这种活动）
					/*
					 * 1、解析规则，找到充值金额所属的档次
					 * 2、增加用户赠券余额
					 * 3、记录日志
					 */

					//1、解析规则，计算出赠券的值
					String activityExtr = topupActivity.getExtr();
					JSONObject jsonObject = JSONObject.parseObject(activityExtr);
					List<Integer> keyList = new ArrayList<Integer>();
					for (String key : jsonObject.keySet()) {
						keyList.add(Integer.valueOf(key));
					}
					Collections.sort(keyList);
					int changeCoupon = 0;
					
					//计算赠券
					for (int index = 0; index < keyList.size(); index++) {
						Integer moneyLevel = keyList.get(index);
						if (moneyLevel > topupMoney) {
							if (index == 0) {
								//最低的送券标准都没达到，不送券
								return;
							}
							if (index > 0) {
								// 如果没有达到下个标准的送券，送上个标准的券
								changeCoupon = jsonObject.getIntValue(keyList.get(index - 1).toString());
								break;
							}
							if (index == keyList.size() - 1) {
								// 达到最高的送券标准，送最高标准的券
								changeCoupon = jsonObject.getIntValue(keyList.get(index).toString());
							}
						}
					}
					if (changeCoupon == 0)
						return;

					//2、增加用户赠券余额
					int beforeCoupon = userInfo.getCoupon();
					int afterCoupon = beforeCoupon + changeCoupon;
					userInfo.setCoupon(afterCoupon);
					userInfoService.update(userInfo);

					//3、记录日志
					UserMoneyLog userMoneyLog = new UserMoneyLog();
					userMoneyLog.setUserId(userInfo.getId());
					userMoneyLog.setSourceType("t_topup_activity");
					userMoneyLog.setSourceId(topupActivity.getId());
					userMoneyLog.setChangeType(UserMoneyChangeTypeEnum.ADD.getKey());
					userMoneyLog.setBeforeMoney(userInfo.getMoney());
					userMoneyLog.setChangeMoney(0);
					userMoneyLog.setAfterMoney(userInfo.getMoney());
					userMoneyLog.setBeforeCoupon(beforeCoupon);
					userMoneyLog.setChangeCoupon(changeCoupon);
					userMoneyLog.setAfterCoupon(afterCoupon);
					userMoneyLog.setCreateTime(new Date());
					userMoneyLog.setUpdateTime(new Date());
					userMoneyLogService.insert(userMoneyLog);
				}
			}
		}
	}
}
